package com.assets.Receive;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.*;

import com.assets.Adapter.Addrepairs_Adapter1;
import com.assets.Adapter.Addrepairs_Adapter_new;
import com.assets.Check.newTanWanCheck.BaseActivity1;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.Scan.qrcode.util.Constant;
import com.assets.Scan.zxing.activity.CaptureActivity;
import com.assets.Scrap.Scrap_Add;
import com.assets.bean.AddRepairs_bean1;
import com.assets.newNHF.util.LogUtils;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Asset;
import com.assets.room.entity.Receives;
import com.assets.room.entity.ReceivesDetail;
import com.assets.room.entity.ReceivesReapply;
import com.assets.util.IdWorkerUtil;
import com.assets.util.MyRFIDHandle;
import com.assets.util.RFIDClientUtil;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;

import okhttp3.*;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class Grant_rfid extends BaseActivity1 {
    private ImageView fh;//返回
    private Button check;
    private String url = "http://" + Url.IP + "/api/receivesInspect";
    private String urls = "http://" + Url.IP + "/api/receivesPut";
    private String rfid_url = "http://" + Url.IP + "/api/receivesInspectRfid";
    private List<AddRepairs_bean1> data = new ArrayList<>();
    private List<String> lv_data = new ArrayList<>();//判断是否重复
    private TextView title_text;//标题
    private ListView Supplies_list;
    private EditText et_number;
    private String receivesId, status;//领用单号。状态
    private Handler handler = new Handler();
    private Button bt_scan, bt_upload, btn_rfid;//rfid,扫码，上传

    private static final String TAG = "这个是领用详情盘点页面";
    private String num;
    private Asset asset;
    private List<Asset> assets;
    private String name;
    private String rfid;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grant_rfid);
        HandlerThread htHandlerThread = new HandlerThread("");
        htHandlerThread.start();
        initView();
        initData();
        initRFID();
    }

    public void initView() {//初始化控件



        btn_rfid = findViewById(R.id.btn_rfid);
        check = (Button) findViewById(R.id.check);
        fh = (ImageView) findViewById(R.id.fh);
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("发放");
        Supplies_list = (ListView) findViewById(R.id.Supplies_list);
        bt_scan = (Button) findViewById(R.id.scan);
        bt_upload = (Button) findViewById(R.id.upload);
        et_number = (EditText) findViewById(R.id.Input_number);
        et_number.setFocusableInTouchMode(true);
        et_number.requestFocus();
        Supplies_list.setOnItemLongClickListener((parent, view, position, id) -> {
            new AlertView(" 提示！", "确认删除", "取消", new String[]{"确定"}, null, Grant_rfid.this, AlertView.Style.Alert, (o, position1) -> {
                if (position1 == 0) {
                    lv_data.remove(position);
                    data.remove(position);
                    Addrepairs_Adapter1 adapter_item = new Addrepairs_Adapter1(Grant_rfid.this, R.layout.addrepairs_item_new, data, "领用");
                    Supplies_list.setAdapter(adapter_item);
                }
            }).setCancelable(true).show();
            return true;
        });
    }

    public void initData() {//初始化数据


//        intent.putExtra("coding_name", getIntent().getStringExtra("coding_name"));
//        intent.putExtra("status", getIntent().getStringExtra("status"));
//        intent.putExtra("reapplyId", list.get(position).get("reapplyId").toString());
//        intent.putExtra("sum", list.get(position).get("creator").toString());


        Intent intent = getIntent();

        String a = intent.getStringExtra("coding_name");
        String b = intent.getStringExtra("status");
        String c = intent.getStringExtra("reapplyId");
        num = intent.getStringExtra("sum");
        name = intent.getStringExtra("name");

        Log.d(TAG, "a: " + a + ", b: " + b + ", c: " + c + ", d: " + num);


        receivesId = intent.getStringExtra("coding_name");
        status = intent.getStringExtra("status");
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        bt_upload.setOnClickListener(v -> {
            if (lv_data.size() > 0) {
                new AlertView(" 提示！", "是否上传数据", "取消", new String[]{"确定"}, null, Grant_rfid.this, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position == 0) {
                            uploads();
                        }
                    }
                }).setCancelable(true).setOnDismissListener(o -> {

                }).show();
            } else {
                showToast("请扫描需要发放的资产");
            }
        });
        check.setOnClickListener(v -> {
            Intent intent1 = new Intent(Grant_rfid.this, Receive_issued.class);
            intent1.putExtra("coding_name", receivesId);
            intent1.putExtra("status", status);
            startActivity(intent1);
        });
        et_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                et_number.selectAll();
                Log.d(TAG, "et_number: " + et_number.getText().toString());
                if (!et_number.getText().toString().trim().equals("") && et_number.length() > 9) {
                    if (!lv_data.contains(et_number.getText().toString().trim())) {
                        upload(et_number.getText().toString().trim());
                    } else {
                        showToast("此资产已存在列表");
                    }

                } else {
                   //错误的格式
                    //这个是可能扫码扫到空的，或者不是的就不管他

                }
            }
        });
        fh.setOnClickListener(v -> finish());
        bt_scan.setOnClickListener(v -> startQrCode());
    }

    // 开始扫码
    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(Grant_rfid.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Grant_rfid.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(Grant_rfid.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Grant_rfid.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(Grant_rfid.this, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Grant_rfid.this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Grant_rfid.this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            final String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            if (lv_data.contains(scanResult)) {
                Toast.makeText(Grant_rfid.this, "该资产已存在列表", Toast.LENGTH_SHORT).show();
                return;
            }
            upload(scanResult);
        }
    }


    private void upload(final String scanResult) {
        showDialog("查询数据");
//        new Thread(() -> {
//            LogUtils.d(lv_data.size() + "sum" + Integer.parseInt(getIntent().getStringExtra("sum")));
            if (lv_data.size() >= Integer.parseInt(getIntent().getStringExtra("sum"))) {
                showToast("领用发放数量不能超过申请数量");
                canDialog();
                return;
            }

        Map<String, Object> map = new HashMap<>();

        map.put("state", "0");
//        Receives allReceives = MyDataBase.init(Grant_rfid.this).receivesDao().getAllReceives(receivesId);
//        if (allReceives != null) {

            asset = MyDataBase.init(Grant_rfid.this).assetDao().queryAllByIdSao(scanResult);
            if (asset != null) {
                if (asset.getStatus().equals("4") || asset.getStatus().equals("13")) {

//                    MyDataBase.init(Grant_rfid.this).assetDao().updateStatus("1", scanResult);
                    map.put("asset", asset);
                    map.put("state", "1");
                }
            }else {
                //如果不是闲置和新资产就不管他
                map.put("state", "3");
            }

//        }else {
//            map.put("state","4");
//        }


        if (map.get("state").equals("0")) {
            showToast("失败");
            canDialog();
        }else if (map.get("state").equals("1")) {
            String assetName = asset.getAssetName();
            String deptId = asset.getDeptId();
            String assetNumber = asset.getAssetNumber();
            String userId = asset.getUserId();
            String model = asset.getModel();
            String type = asset.getType();
            String jifan = asset.getFinancialCode();

            String jigui = asset.getAccountant();
            if (lv_data.size() >= Integer.parseInt(getIntent().getStringExtra("sum"))) {
                showToast("领用发放数量不能超过申请数量");
                return;
            }
            lv_data.add(scanResult);
            String remark = asset.getRemark();
            data.add(new AddRepairs_bean1("", assetName, asset.getCreatedate(), assetNumber, MyDataBase.init(Grant_rfid.this).userDao().getNameByIds(userId) == null? "暂无使用人" : MyDataBase.init(Grant_rfid.this).userDao().getNameByIds(userId) , model, MyDataBase.init(Grant_rfid.this).typeDao().getNameById(type) == null ? "暂无类别" : MyDataBase.init(Grant_rfid.this).typeDao().getNameById(type), remark, "类别", "", jifan, jigui));

//            data.add(new AddRepairs_bean1("", assetName, deptId, assetNumber, userId, model, type, remark, "类别", "", jifan, jigui));
            Collections.reverse(data);
            Addrepairs_Adapter_new adapter_item = new Addrepairs_Adapter_new(Grant_rfid.this, R.layout.addrepairs_item_new, data, "领用");
            Supplies_list.setAdapter(adapter_item);
            canDialog();
        }else if (map.get("state").equals("2")) {
            showToast("未申请此类型的资产");
        }
        if (map.get("state").equals("3")) {
            showToast("非闲置资产");
        }
        if (map.get("state").equals("4")) {
            showToast("资产不存在");
        }
        if (map.get("state").equals("5")) {
            showToast("资产非领用事业部所有");
        }



//            OkHttpClient client = new OkHttpClient
//                    .Builder()
//                    .hostnameVerifier(new AllowAllHostnameVerifier())
//                    .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
//                    .connectTimeout(10, TimeUnit.SECONDS)//连接超时
//                    .readTimeout(500, TimeUnit.SECONDS)
//                    .build();//创建OkHttpClient对象。
//            FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
//            formBody.add("assetNumber", scanResult)
//                    .add("receivesId", receivesId); //传递键值对参数
//            Request request = new Request.Builder()//创建Request 对象。
//                    .url(url)
//                    .post(formBody.build())//传递请求体
//                    .build();
//            client.newCall(request).enqueue(new Callback() {
//                @Override
//                public void onFailure(Call call, IOException e) {
//                    //回调方法的使用与get异步请求相同
//                    Log.i("123123", "error");
//                    showToast("查询失败，请重试");
//                    canDialog();
//                }
//
//                @Override
//                public void onResponse(Call call, Response response) throws IOException {
//                    final String responseData = response.body().string();
//                    //回调方法的使用与get异步请求相同
//                    handler.post(() -> {
//                        try {
//                            LogUtils.d(responseData);
//                            JSONObject json = new JSONObject(responseData);
//                            if (json.getString("state").equals("0")) {
//                                showToast("失败");
//                            }
//                            if (json.getString("state").equals("1")) {
//                                lv_data.add(scanResult);
//                                JSONObject jsonObject = json.getJSONObject("asset");
//                                String assetName = jsonObject.getString("assetName");
//                                String deptId = jsonObject.getString("deptId");
//                                String assetNumber = jsonObject.getString("assetNumber");
//                                String userId = jsonObject.getString("userId");
//                                String model = jsonObject.getString("model");
//                                String type = jsonObject.getString("type");
//                                String remark = jsonObject.getString("remark");
//                                String image = jsonObject.getString("image");
//                                if (!TextUtils.isEmpty(image)) {
//                                    image = "http://" + Url.IP + image;
//                                }
//                                Collections.reverse(data);
//                                data.add(new AddRepairs_bean1(image, assetName, deptId, assetNumber, userId, model, type, remark, "类别", ""));
//                                Collections.reverse(data);
//                                Addrepairs_Adapter1 adapter_item = new Addrepairs_Adapter1(Grant_rfid.this, R.layout.addrepairs_item, data);
//                                Supplies_list.setAdapter(adapter_item);
//                            }
//                            if (json.getString("state").equals("2")) {
//                                showToast("未申请此类型的资产");
//                            }
//                            if (json.getString("state").equals("3")) {
//                                showToast("非闲置资产");
//                            }
//                            if (json.getString("state").equals("4")) {
//                                showToast("资产不存在");
//                            }
//                            if (json.getString("state").equals("5")) {
//                                showToast("资产非领用事业部所有");
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        } finally {
//                            canDialog();
//                        }
//                    });
//                }
//            });
//        }).start();
    }

    /**
        提交按钮
    */
    private void uploads() {

        Log.d("提交的数据", "receivesId ===>> " + receivesId);

        Log.d("提交的数据", "assetNumber ===>> " + new Gson().toJson(data));

        List<ReceivesDetail> receivesDetailList = new ArrayList<>();

        /**
         data是加进去的RFID或者是扫码的内容
         */

        for (int i = 0; i < data.size(); i++) {

            //这个是获取到资产里面的asset_number
            String assetNumber = data.get(i).getCode_number();

            //更新资产的状态，更新成再用状态
            MyDataBase.init(Grant_rfid.this).assetDao().updateStatusByNumber("1", "1", assetNumber);

//            MyDataBase.init(Grant_rfid.this).receivesDetailDao().updateFlag("1");

            ReceivesDetail receivesDetail = new ReceivesDetail();
            receivesDetail.setReceivesDetailId(Long.valueOf(IdWorkerUtil.getInstance(1L).generateUniqueId(19)));
            receivesDetail.setAssetId(data.get(i).getCode_number());
            receivesDetail.setIsFlag("1");
            //1 已归还  2 未归还
            receivesDetail.setIsreturn("2");
            receivesDetail.setReceivesId(receivesId);
            receivesDetailList.add(receivesDetail);

        }
        MyDataBase.init(Grant_rfid.this).receivesDetailDao().insertReceivesDetail(receivesDetailList);

//        List<String> roomAssetId = MyDataBase.init(Grant_rfid.this).receivesDetailDao().getAssetById(receivesId);
//
//        for (String assetId : roomAssetId) {
//
//            if (MyDataBase.init(Grant_rfid.this).assetDao().queryAllByIds(assetId, "1") != null) {
//                assets = MyDataBase.init(Grant_rfid.this).assetDao().queryAllByIds(assetId, "1");
//            }else {
//             return;
//            }
//
//        }

        int size = data.size();
//        List<String> num = MyDataBase.init(Grant_rfid.this).receivesReapplyDao().getNameByIds(receivesId);
//        int sum = 0;
//        for(String str : num) {
//            sum += Integer.parseInt(str);
//        }

//        String size2 = MyDataBase.init(Grant_rfid.this).receivesReapplyDao().getSumById(receivesId);
        String size2 = MyDataBase.init(Grant_rfid.this).receivesReapplyDao().getSumByName(name);

        int roomSize = Integer.parseInt(size2);


        if (roomSize - size == 0) {
//            name
            MyDataBase.init(Grant_rfid.this).receivesReapplyDao().updateIsAudits("1", "1", name);
//            MyDataBase.init(Grant_rfid.this).receivesDao().updateStatus1("3", "1", receivesId);
            MyDataBase.init(Grant_rfid.this).receivesDao().updateStatus2(new SimpleDateFormat("yyyy-MM-dd").format(new Date()), "1", receivesId);
        }else if (roomSize - size > 0){

            MyDataBase.init(Grant_rfid.this).receivesDao().updateStatus1("4", "1", receivesId);

        }

//        List<ReceivesReapply> reapplys3 = MyDataBase.init(Grant_rfid.this).receivesReapplyDao().getOn1Data("0", receivesId);
//        int snum3 = 0;
        if (MyDataBase.init(Grant_rfid.this).receivesReapplyDao().getOn1Data("0", receivesId).size() == 0) {

            MyDataBase.init(Grant_rfid.this).receivesDao().updateStatus1("3", "1", receivesId);

        }
//


        showToast("提交成功");
        finish();

//        new Thread(() -> {
//            OkHttpClient client = new OkHttpClient
//                    .Builder()
//                    .hostnameVerifier(new AllowAllHostnameVerifier())
//                    .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
//                    .connectTimeout(10, TimeUnit.SECONDS)//连接超时
//                    .readTimeout(500, TimeUnit.SECONDS)
//                    .build();//创建OkHttpClient对象。
//            FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
//            String reapplyId = getIntent().getStringExtra("reapplyId");
//            formBody.add("assetNumbers", lv_data.toString())
//                    .add("receivesId", receivesId)
//                    .add("reapplyId", reapplyId); //传递键值对参数
//            LogUtils.d(lv_data.toString() + "receivesId:" + receivesId + "reapplyId" + reapplyId);
//            Request request = new Request.Builder()//创建Request 对象。
//                    .url(urls)
//                    .post(formBody.build())//传递请求体
//                    .build();
//            client.newCall(request).enqueue(new Callback() {
//                @Override
//                public void onFailure(Call call, IOException e) {
//                    //回调方法的使用与get异步请求相同
//                    Log.i("123123", "error");
//                }
//
//                @Override
//                public void onResponse(Call call, Response response) throws IOException {
//                    final String responseData = response.body().string();
//                    LogUtils.d(responseData);
//                    //回调方法的使用与get异步请求相同
//                    handler.post(() -> {
//                        try {
//                            JSONObject json = new JSONObject(responseData);
//                            if (json.getString("state").equals("0")) {
//                                showToast("上传失败");
//                            }
//                            if (json.getString("state").equals("1")) {
//                                showToast("上传成功");
//                                setResult(1);
//                                finish();
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    });
//                }
//            });
//        }).start();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private RFIDClientUtil rfidClientUtil;
    private Map<String, String> map = new HashMap<>();

    private void initRFID() {
        MyRFIDHandle myRFIDHandle = new MyRFIDHandle();
        myRFIDHandle.post(() -> {
            rfidClientUtil = new RFIDClientUtil(epc -> {
                if (map.containsKey(epc)) {
                    return;
                }
                map.put(epc, "");
                RFID(epc);
            });
            rfidClientUtil.setRequestStop(() -> runOnUiThread(() -> {
                btn_rfid.setText("开始读取");
            }));
            rfidClientUtil.setRequestRead(() -> runOnUiThread(() -> {
                btn_rfid.setText("停止读取");
            }));
            getLifecycle().addObserver(myRFIDHandle);
            getLifecycle().addObserver(rfidClientUtil);
        });
        btn_rfid.setOnClickListener(v -> {
            String rfidTitle = btn_rfid.getText().toString();
            if (rfidTitle.equals("开始读取")) {
                rfidClientUtil.read();
            } else {
                rfidClientUtil.stop();
            }
        });
    }

    private void RFID(String RFID) {
        new Thread(() -> {

            Log.d("读到的RFID是什么", "RFID ==== >" + RFID);

            if (RFID.length() > 16) {
                rfid = RFID.substring(0, 16);
            }else {
                rfid = RFID;
            }



            if (lv_data.size() >= Integer.parseInt(num)) {
                showToast("领用发放数量不能超过申请数量");
                return;
            }

            Map<String, Object> map = new HashMap<>();
            Asset asset1 = MyDataBase.init(Grant_rfid.this).assetDao().queryAllById(rfid);
//            if (asset1 == null) {
//                return;
//            }
            map.put("state", "0");
//            Receives allReceives = MyDataBase.init(Grant_rfid.this).receivesDao().getAllReceives(receivesId);
//            if (allReceives != null) {


                if (asset1 != null) {
                    if (asset1.getStatus().equals("4") || asset1.getStatus().equals("13")) {

//                        MyDataBase.init(Grant_rfid.this).assetDao().updateStatus("1","1", RFID);
                        map.put("asset", asset1);
                        map.put("state", "4");
                    }else if (asset1.getStatus().equals("1")){
                        map.put("state", "1");
                    }
                }else {
                    //如果不是闲置和新资产就不管他
                    map.put("state", "3");
                }

//            }else {
//                map.put("state","7");
//            }


            if (map.get("state").equals("0")) {
                showToast("失败");
            }else if (map.get("state").equals("3")) {
                showToast("未知的rfid");
            }
            else if (map.get("state").equals("1")) {
                showToast("该资产已领用");
            }else if (map.get("state").equals("4")) {
                String assetName = asset1.getAssetName();
                String deptId = MyDataBase.init(Grant_rfid.this).deptDao().getNameById(asset1.getDeptId());
                String assetNumber = asset1.getAssetNumber();
                String userId = MyDataBase.init(Grant_rfid.this).userDao().getNameById(asset1.getUserId()) == null ? "暂无此人" : MyDataBase.init(Grant_rfid.this).userDao().getNameById(asset1.getUserId());
                String model = asset1.getModel();
                String jifan = asset1.getFinancialCode();
                String jigui = asset1.getAccountant();
                String type = MyDataBase.init(Grant_rfid.this).typeDao().getNameById(asset1.getType());
                if (lv_data.size() >= Integer.parseInt(getIntent().getStringExtra("sum"))) {
                    showToast("领用发放数量不能超过申请数量");
                    return;
                }
                lv_data.add(assetNumber);
                String remark = asset1.getRemark();
                data.add(new AddRepairs_bean1("", assetName, asset1.getCreatedate(), assetNumber, MyDataBase.init(Grant_rfid.this).userDao().getNameByIds(userId) == null? "暂无使用人" : MyDataBase.init(Grant_rfid.this).userDao().getNameByIds(userId) , model, MyDataBase.init(Grant_rfid.this).typeDao().getNameById(type) == null ? "暂无类别" : MyDataBase.init(Grant_rfid.this).typeDao().getNameById(type), remark, "类别", "", jifan, jigui));
                Collections.reverse(data);
                Addrepairs_Adapter_new adapter_item = new Addrepairs_Adapter_new(Grant_rfid.this, R.layout.addrepairs_item, data, "领用");
                runOnUiThread(()-> {Supplies_list.setAdapter(adapter_item);});

//            }else if (map.get("state").equals("2")) {
//                showToast("未申请此类型的资产");
//            }
//            if (map.get("state").equals("3")) {
//                showToast("非闲置资产");
//            }
//            if (map.get("state").equals("4")) {
//                showToast("资产不存在");
//            }
//            if (map.get("state").equals("5")) {
//                showToast("资产非领用事业部所有");
//            }



//            LogUtils.d(RFID);
//            OkHttpClient client = new OkHttpClient
//                    .Builder()
//                    .hostnameVerifier(new AllowAllHostnameVerifier())
//                    .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
//                    .connectTimeout(10, TimeUnit.SECONDS)//连接超时
//                    .readTimeout(500, TimeUnit.SECONDS)
//                    .build();//创建OkHttpClient对象。
//            FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
//            formBody.add("rfid", RFID).add("receivesId", receivesId); //传递键值对参数
//            Request request = new Request.Builder()//创建Request 对象。
//                    .url(rfid_url)
//                    .post(formBody.build())//传递请求体
//                    .build();
//            client.newCall(request).enqueue(new Callback() {
//                @Override
//                public void onFailure(Call call, IOException e) {
//                    //回调方法的使用与get异步请求相同
//                    Log.i("123123", "error");
//                    map.remove(RFID);
//                }
//
//                @Override
//                public void onResponse(Call call, Response response) throws IOException {
//                    final String responseData = response.body().string();
//                    LogUtils.d(responseData);
//                    //回调方法的使用与get异步请求相同
//                    handler.post(() -> {
//                        try {
//                            JSONObject json = new JSONObject(responseData);
//                            if (json.getString("state").equals("0")) {
//                                showToast("失败");
//                            }
//                            if (json.getString("state").equals("1")) {
//                                JSONObject jsonObject = json.getJSONObject("asset");
//                                String assetName = jsonObject.getString("assetName");
//                                String deptId = jsonObject.getString("deptId");
//                                String assetNumber = jsonObject.getString("assetNumber");
//                                String userId = jsonObject.getString("userId");
//                                String model = jsonObject.getString("model");
//                                String type = jsonObject.getString("type");
//                                if (lv_data.size() >= Integer.parseInt(getIntent().getStringExtra("sum"))) {
//                                    showToast("领用发放数量不能超过申请数量");
//                                    return;
//                                }
//                                lv_data.add(assetNumber);
//                                String remark = jsonObject.getString("remark");
//                                String image = jsonObject.optString("image");
//                                if (!TextUtils.isEmpty(image)) {
//                                    image = "http://" + Url.IP + image;
//                                }
//                                Collections.reverse(data);
//                                data.add(new AddRepairs_bean1(image, assetName, deptId, assetNumber, userId, model, type, remark, "类别", ""));
//                                Collections.reverse(data);
//                                Addrepairs_Adapter1 adapter_item = new Addrepairs_Adapter1(Grant_rfid.this, R.layout.addrepairs_item, data);
//                                Supplies_list.setAdapter(adapter_item);
//                            }
//                            if (json.getString("state").equals("2")) {
//                                showToast("未申请此类型的资产");
//                            }
//                            if (json.getString("state").equals("3")) {
//                                showToast("非闲置资产");
//                            }
//                            if (json.getString("state").equals("4")) {
//                                showToast("资产不存在");
//                            }
//                            if (json.getString("state").equals("5")) {
//                                showToast("资产非领用事业部所有");
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    });
                }
//            });
        }).start();
    }

}
